<template>
  <view>
      <view v-if="isLoad === null" class="margin-top load notexist text-l load-project"></view>
      <view v-if="isLoad === false" class="margin-top load loading text-l load-project"></view>
      <block v-if="isLoad">
          <image :src="teacher.avatar" mode="widthFix" class="loading cover" :lazy-load="true" />
          <view class="main">
              <view class="title-box">
                  <view class="mark">{{ teacher.teacherName }}</view>
                  <view class="left">
                      <image @tap="url" :data-url="teacher.avatar" data-type="image" mode="aspectFill" class="loading shadow" :src="teacher.avatar" />
                  </view>
                  <view class="right">
                      <view class="line1">{{ teacher.teacherName }}</view>
                      <view class="line2">
                          <view class="tag-list">
                              <text v-for="(itm, index) in teacher.tagList" :key="index">{{ itm }}</text>
                          </view>
                      </view>
                      <view class="line3">
                          <view class="star">
                              <text class="icon-favorfill cur" v-for="(item, index) in teacher.starLevel" :key="index"></text>
                              <text class="icon-favor text-grey" v-for="(item, index) in 5 - teacher.starLevel" :key="index"></text>
                          </view>
                      </view>
                  </view>
              </view>
              <view class="detail-box">
                  <view class="meet-tab">
                      <view @tap="bindTabTap" data-cur="mind" :class="'item ' + (cur == 'mind' ? 'cur' : '')">老师简介</view>
                      <view @tap="bindTabTap" data-cur="time" :class="'item ' + (cur == 'time' ? 'cur' : '')">预约时段</view>
                  </view>

                  <view v-if="cur == 'mind'" class="article-box">
                      <view class="article" v-if="teacher.formResList && teacher.formResList.length > 0">
                          <block v-for="(item, index) in teacher.formResList" :key="index">
                              <view class="content" v-if="item.type == 'text'">
                                  <text :user-select="true">{{ item.val }}</text>
                              </view>

                              <view class="pics" v-if="item.type == 'img'">
                                  <image
                                      @tap="url"
                                      data-type="img"
                                      :data-url="item.val"
                                      :show-menu-by-longpress="true"
                                      class="loading"
                                      mode="widthFix"
                                      :lazy-load="true"
                                      :src="item.val"
                                  ></image>
                              </view>
                          </block>
                      </view>
                  </view>

                  <block v-if="cur == 'time'">
                      <block v-if="days.length > 0">
                          <scroll-view scroll-x="true" class="date" enable-flex="true">
                              <view @tap="bindDayTap" :data-idx="index" class="date-inner" v-for="(item, index) in days" :key="index">
                                  <view :class="'item ' + (dayIdx == index ? 'cur' : '')">
                                      <text v-if="dayIdx == index && item.status != '今天'" class="status cur"><text class="icon-check"></text></text>
                                      <text v-else :class="'status ' + (item.status == '今天' ? 'bg-red' : '')">{{ item.status || '可约' }}</text>
                                      <text class="week">{{ item.week }}</text>
                                      <text class="day">{{ item.day }}</text>
                                  </view>
                              </view>
                          </scroll-view>

                          <view class="time-title">请选择时段</view>
                          <view class="time">
                              <view
                                  @tap="bindTimeTap"
                                  :data-timeidx="idx"
                                  :class="'item ' + (timeIdx == idx ? 'cur' : '') + ' ' + (itm.error ? 'selected' : '')"
                                  v-for="(itm, idx) in days[dayIdx].times"
                                  :key="idx"
                              >
                                  <block v-if="!itm.error">
                                      <text v-if="timeIdx != idx" class="status">可约</text>
                                      <text v-else class="status"><text class="icon-check"></text></text>
                                  </block>

                                  <text class="t1">{{ index }}{{ itm.start }}~{{ itm.end }}</text>

                                  <text v-if="!itm.error && itm.isLimit && itm.maxBookings > 1" class="t3">剩余:{{ itm.maxBookings - itm.bookedCount }}</text>

                                  <text v-if="!itm.error && !itm.isLimit" class="t3">人数不限</text>

                                  <text v-if="itm.error" class="t3">{{ itm.error }}</text>
                              </view>
                          </view>
                          <View style="height: 250rpx"></View>
                      </block>
                      <view v-else-if="days.length == 0" class="margin-top load notexist text-l load-project day-load"></view>
                      <view v-else class="margin-top load loading text-l load-project"></view>
                  </block>
              </view>
          </view>

          <view v-if="days.length > 0" class="bottom safe-bottom">
              <view class="inner">
                  <view class="line2">
                      <view v-if="timeIdx > -1" class="left text-red">
                          {{ days[dayIdx].day + ' ' + days[dayIdx].times[timeIdx].start + '~' + days[dayIdx].times[timeIdx].end }}
                      </view>
                      <view v-else class="left text-red">未选定预约时段</view>
                      <view @tap="bindJoinTap" class="right">去预约</view>
                  </view>
              </view>
          </view>

         <cmpt-detail
              :doTop="true"
              mode="left"
              :topBtnShow="topBtnShow"
              topBtnBottom="150"
              tag=""
              :oid="id"
              cate=1
              :title="teacher.teacherName"
              :cover="teacher.avatar"
              :qr="teacher.qrCode"
              desc="查看详情"
              :bg="skin.PROJECT_COLOR"
          ></cmpt-detail>
      </block>
  </view>
</template>

<script>
import cmptDetail from '@/cmpts/biz/detail/detail_cmpt';
const cloudHelper = require('@/utils/helper/cloud_helper.js');
const pageHelper = require('@/utils/helper/page_helper.js');
const timeHelper = require('@/utils/helper/time_helper.js');
const MeetBiz = require('@/utils/biz/meet_biz.js');
const projectSetting = require('@/utils/public/project_setting.js');
const ProjectBiz = require('@/utils/biz/project_biz.js');
const PassportBiz = require('@/utils/comm/biz/passport_biz.js');
const { getTeacherDetail,getTeacherDays } = require('@/api/api.js');
const api = require('@/api/api.js');

export default {
  components: {
      cmptDetail
  },
  data() {
      return {
          isLoad: false,
          tabCur: 0,
          mainCur: 0,
          verticalNavTop: 0,
          cur: 'mind',
          dayIdx: 0,
          timeIdx: -1,
          topBtnShow: false,

          teacher: {
              MEET_OBJ: {
                  cover: '',
                  tag: [],
                  level: [],
                  content: ''
              },

              MEET_CATE_NAME: '',
              MEET_TITLE: '',
              MEET_QR: ''
          },
          days: [{
            day: '2025-07-11',
            week: '周二',
            date: '07-11',
            // status: '可约',
            times: [{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            }]
          },{
            day: '2025-07-11',
            week: '周二',
            date: '07-11',
            // status: '可约',
            times: [{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            },{
              start: '10:00',
              end: '12:00',
              error: false,
              isLimit: false,
              limit: 0,
            }]
          }
        
        ],
          canNullTime: '',

          itm: {
              title: '',
              error: false,
              start: '',
              end: '',
              isLimit: '',
              limit: 0,

              stat: {
                  succCnt: 0
              }
          },

          times: [],
          day: '',
          start: '',
          end: '',
          id: '',

          skin: {
              PROJECT_COLOR: ''
          }
      };
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      ProjectBiz.initPage(this);
      // if (!pageHelper.getOptions(this, options)) {
      //     return;
      // }
      this.id = options.id;
      this.loadDetailFun();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: async function () {
      await this.loadDetailFun();
      uni.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
      return {
          title: this.meet.MEET_TITLE,
          imageUrl: this.meet.MEET_OBJ.cover[0]
      };
  },
  onPageScroll: function (e) {
      if (e.scrollTop > 100) {
          this.setData({
              topBtnShow: true
          });
      } else {
          this.setData({
              topBtnShow: false
          });
      }
  },
  methods: {
      loadDetailFun: async function () {
        //   this.id = 1;
          this.setData({
              dayIdx: 0,
              timeIdx: -1,
              isLoad: false
          });
          let id = this.id;
          if (!id) {
              return;
          }
        //   let params = {
        //       id
        //   };
          let opt = {
              title: 'bar'
          };
          let teacher = await getTeacherDetail(this.id);
          let tagList = teacher.tags.split(',');
          teacher.tagList = tagList;
          this.teacher = teacher;
          console.log('teacher', teacher);
          // let meet = await cloudHelper.callCloudData('meet/view', params, opt);
          if (!teacher) {
              this.setData({
                  isLoad: null
              });
              return;
          }
        //  console.log('teacher', teacher);
         let params = {
            id: this.id
         }
         let days = await getTeacherDays(params);
        //  console.log('days', days);
        this.days = days;
        //   console.log('teacher.days', this.days );

        //   // 生成未来5天的展示数据
        //   const buildTimes = () => [
        //       { start: '10:00', end: '12:00', error: false, isLimit: false, limit: 0, stat: { succCnt: 0 },mark: '10:00-12:00' },
        //       { start: '13:00', end: '15:00', error: false, isLimit: false, limit: 0, stat: { succCnt: 0 },mark: '13:00-15:00' },
        //       { start: '15:00', end: '17:00', error: false, isLimit: false, limit: 0, stat: { succCnt: 0 },mark: '15:00-17:00' },
        //       { start: '19:00', end: '20:00', error: false, isLimit: false, limit: 0, stat: { succCnt: 0 },mark: '19:00-20:00' },
        //       { start: '20:00', end: '21:00', error: false, isLimit: false, limit: 0, stat: { succCnt: 0 },mark: '20:00-21:00' },
        //       { start: '21:00', end: '22:00', error: false, isLimit: false, limit: 0, stat: { succCnt: 0 },mark: '21:00-22:00' }
        //   ];

        //   let days = [];
        //   for (let k = 0; k < 8; k++) {
        //       const curDay = timeHelper.time('Y-M-D', 86400 * k);
        //       let status = '';
        //       if (k === 0) status = '今天';
        //       if (k === 1) status = '明天';
        //       if (k === 2) status = '后天';
        //       days.push({
        //           day: curDay,
        //           week: timeHelper.week(curDay),
        //           date: curDay.split('-')[1] + '-' + curDay.split('-')[2],
        //           status,
        //           times: buildTimes()
        //       });
        //   }

        //   this.setData({
        //       days
        //   });

          this.isLoad = true;
          // this.setData({
          //     isLoad: true,
          //     meet,
          //     days,
          //     canNullTime: projectSetting.MEET_CAN_NULL_TIME
          // });
      },

      bindDayTap: function (e) {
          let dayIdx = pageHelper.dataset(e, 'idx');
          this.setData({
              dayIdx,
              timeIdx: -1
          });
      },

      bindTimeTap: function (e) {
          let timeIdx = pageHelper.dataset(e, 'timeidx');
          let node = this.days[this.dayIdx].times[timeIdx];
          if (node.error) {
              return;
          }
          this.setData({
              timeIdx
          });
      },

      bindJoinTap: async function (e) {
        const result = await PassportBiz.requireLogin();
        if(result == false){
          return;
        }
          this.setData({
              cur: 'time'
          });
          let dayIdx = this.dayIdx;
          let timeIdx = this.timeIdx;
          if (timeIdx < 0) {
              return pageHelper.showNoneToast('请先选择预约时段');
          }
          let time = this.days[dayIdx].times[timeIdx];
          if (time.error) {
              if (time.error.includes('预约')) {
                  return pageHelper.showModal('该时段' + time.error + '，换一个时段试试吧！');
              } else {
                  return pageHelper.showModal('该时段预约' + time.error + '，换一个时段试试吧！');
              }
          }
          let teacherId = this.id;
          let timeId = time.id;
          let callback = async () => {
              try {
                  let opts = {
                      title: '请稍候'
                  };
                  let params = {
                      teacherId: teacherId,
                      timeId: timeId
                  };
                  await api.before_join(params, opts).then((res) => {
                      uni.navigateTo({
                          url: `/pages/meet/join/meet_join?id=${teacherId}&timeId=${timeId}`
                      });
                  });
              } catch (ex) {
                  console.log('CatchClause', ex);
                  console.log('CatchClause', ex);
                  console.log(ex);
              }
          };
          callback();
      },

      url: function (e) {
          pageHelper.url(e, this);
      },

      bindTabTap: function (e) {
          let cur = pageHelper.dataset(e, 'cur');
          this.setData({
              cur
          });
      }
  }
};
</script>
<style>
@import './meet_detail.css';
</style>
